﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Utilities;

namespace DTBuilderLib
{
    /// <summary>
    /// Builds a web site out of the results of the render. Does it "in place", and so expects
    /// a fairly specific directory structure. This is done so as not to have to recompile the
    /// output of the silverlight app.
    /// </summary>
    public class WebSiteBuilder
    {
        /// <summary>
        /// Simple copy operation that copies files from the template over to the renderbase.
        /// This expects (!!!) that renderBase contains a subdir meeting, which contains meeting,
        /// which contains info.bin. If not, then nothing is going to be good!
        /// </summary>
        /// <param name="renderBase"></param>
        /// <returns></returns>
        public static FileInfo CreateWebSite(DirectoryInfo renderBase, string websiteTitle)
        {
            try
            {
                DirectoryInfo templateDir = new DirectoryInfo(ExternalToolLocations.LocationSLTemplateControl);
                CopyFiles(templateDir, renderBase);
                FileInfo testPage = new FileInfo(renderBase + @"\TestPage.html");
                FileInfo finalPage = new FileInfo(renderBase + @"\ViewConference.html");
                if (finalPage.Exists)
                {
                    finalPage.Delete();
                    finalPage.Refresh();
                }
                testPage.MoveTo(finalPage.FullName);
                finalPage.Refresh();
                finalPage.ReplaceText("<title>DeepTalkDisplay</title>", "<title>" + websiteTitle + "</title>");
                finalPage.InsertAsFirstLine("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
                return finalPage;
            }
            catch (Exception e)
            {
                Logger.LogErrorMessage("Failed To Copy Over Website", e.Message);
                throw;
            }
        }

        /// <summary>
        /// Copy files in dir to dest.
        /// </summary>
        /// <param name="dir"></param>
        /// <param name="dest"></param>
        private static void CopyFiles(DirectoryInfo dir, DirectoryInfo dest)
        {
            if (!dest.Exists)
            {
                dest.Create();
            }

            foreach (var d in dir.GetDirectories())
            {
                CopyFiles(d, new DirectoryInfo(dest.FullName + "\\" + d.Name));
            }

            foreach (var f in dir.GetFiles())
            {
                FileInfo destFile = new FileInfo(dest.FullName + "\\" + f.Name);
                if (!destFile.Exists)
                {
                    f.CopyTo(destFile.FullName);
                }
            }
        }
    }
}
